#include "head_2.h"

#define len_Env 24
extern linknode *H_trf;
extern int head_insert(linknode *H, sendEnv value);
extern pthread_cond_t cond_analysis;

extern pthread_mutex_t mutex_linklist;
extern pthread_mutex_t mutex_transfer;

int dev_uart_fd;


void serial_init(int fd){
	struct termios init_options;
	tcgetattr(fd, &init_options);
	init_options.c_cflag |= ( CLOCAL | CREAD );
	init_options.c_cflag &= ~CSIZE;
	init_options.c_cflag &= ~CRTSCTS;
	init_options.c_cflag |= CS8;
	init_options.c_cflag &= ~CSTOPB;
	init_options.c_iflag |= IGNPAR;
	init_options.c_iflag &= ~(ICRNL | IXON);
	init_options.c_oflag = 0;
	init_options.c_lflag = 0;
	
	cfsetispeed(&init_options, B115200);
	cfsetospeed(&init_options, B115200);
	tcsetattr(fd, TCSANOW, &init_options);
}


void *pthread_uart_transfer(){
	
	int len = 0,i = 0;
	sendEnv p;
	
	if((dev_uart_fd = open("/dev/ttyUSB0", O_RDWR, 0666)) < 0){
		perror("fail to open DEV_ZIGBEE");                                                                           
		exit(-1);
	}

	serial_init(dev_uart_fd);
	while(1)
	{
	printf("%d\n",__LINE__);
		if((len = read(dev_uart_fd, &p, sizeof(sendEnv))) != len_Env){
	printf("%d\n",__LINE__);
	printf("%d\n",len);
	
			for(i = len; i < len_Env; i++){
				read(dev_uart_fd,&p + i, 1);
			}
			printf("%d\n",i);
		}
		printf("x = %d\n",p.x);
		
		pthread_mutex_lock (&mutex_linklist);
		head_insert(H_trf,p);
		pthread_mutex_unlock (&mutex_linklist);

		printf("accetp from m0 success!\n");
		pthread_cond_signal (&cond_analysis);
	}

}
